import { Service } from 'egg';
import { Op } from 'sequelize';
import { Result } from '../util/result';
import MsgEnum from '../util/msgEnum';
import { v4 as uuidv4 } from 'uuid';
import { put } from '../util/ossFile';
import RoleEnum from '../util/roleEnum';
import areas from '../util/area';

/**
 * Talent Service
 */
export default class Test extends Service {
  async talentList(page, name, talentType, organization, date) {
    const { ctx } = this;
    console.log(page, name, talentType, organization, date);
    let where;
    if (date && date !== '') {
      where = {
        name: { [Op.like]: `%${name}%` },
        unit: { [Op.like]: `%${organization}%` },
        updateTime: new Date(date),
      };
    } else {
      where = {
        name: { [Op.like]: `%${name}%` },
        unit: { [Op.like]: `%${organization}%` },
      };
    }
    console.log(where);

    return await ctx.model.Talent.findAndCountAll({
      where,
      include: [
        {
          model: ctx.model.ApplicationArea,
        },
        {
          model: ctx.model.TalentClassfication,
          where: {
            typeName: {
              [Op.like]: `%${talentType}%`,
            },
          },
        },
        {
          model: ctx.model.Title,
        },
        {
          model: ctx.model.Position,
        },
        {
          model: ctx.model.OrganizationType,
        },
      ],
      offset: Number((page - 1) * 10),
      limit: 10,
      distinct: true,
    });
  }

  async insertTalent(data, r) {
    const { ctx } = this;
    const exist = await ctx.model.Talent.findAll({
      where: { tel: data.tel },
    });
    if (exist.length !== 0) {
      return new Result({ exist: true }, MsgEnum.PROJUCT_REPEAT);
    }
    let transaction;
    try {
      transaction = await this.ctx.model.transaction();
      const uuid = uuidv4().replace(/-/g, '');

      const today = new Date();
      const now =
        today.getFullYear() +
        '-' +
        (today.getMonth() + 1) +
        '-' +
        today.getDate();

      const talent = await ctx.model.Talent.create(
        {
          uuid,
          name: data.name,
          sex: data.sex,
          age: data.age,
          tel: data.tel,
          email: data.email,
          role: data.title,
          education: data.education,
          fk_applicationArea: data.applicationArea,
          pk_type: data.talentType,
          unit: data.unit,
          filler: data.filler,
          description: data.description,
          address: data.address,
          post: data.position,
          type: data.type,
          updateTime: new Date(now),
        },
        { transaction }
      );
      const { id } = talent;
      console.log('id:', id);

      await transaction.commit();

      if (r.filename !== 'null.pdf') {
        const res = await put(RoleEnum.TALENT, id, r);

        if (res.error) {
          return new Result(null, MsgEnum.SERVER_ERROR);
        }
      }

      return new Result({ upload: true }, MsgEnum.UPLOAD_SUCCESS);
    } catch (e) {
      await transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }

  async delTalent(uuid) {
    const { ctx } = this;

    let transaction;
    try {
      transaction = await this.ctx.model.transaction();
      await ctx.model.Talent.destroy(
        {
          where: {
            uuid: {
              [Op.in]: uuid,
            },
          },
        },
        { transaction }
      );

      await transaction.commit();
      return 'success';
    } catch (err) {
      await transaction.rollback();
      return 'fail';
    }
  }

  async insertTalents(datas, filler) {
    const { ctx } = this;
    console.log('=======================');

    const today = new Date();
    const now =
      today.getFullYear() +
      '-' +
      (today.getMonth() + 1) +
      '-' +
      today.getDate();
    const updateTime = new Date(now);
    let num = 0;

    for (const data of datas) {
      let transaction;
      try {
        transaction = await ctx.model.transaction();
        console.log(data);
        const exist = await ctx.model.Talent.findAll({
          where: { tel: data[10] },
        });
        if (exist.length !== 0) {
          transaction.rollback();
          continue;
        }

        const talent = await ctx.model.Talent.create(
          {
            uuid: uuidv4().replace(/-/g, ''),
            name: data[0],
            sex: data[1] === '男' ? 1 : 0,
            age: data[2],
            unit: data[4] ?? '',
            email: data[11],
            tel: data[10],
            education: data[9],
            address: data[12],
            description: data[13],
            filler,
            updateTime,
          },
          { transaction }
        );
        if (data[5]) {
          const title = await ctx.model.Title.findOne(
            {
              where: {
                name: data[5],
              },
            },
            { transaction }
          );

          await talent.setTitle(title, { transaction });
        }

        if (data[6]) {
          const position = await ctx.model.Position.findOne(
            {
              where: {
                name: data[6],
              },
            },
            { transaction }
          );
          await talent.setPosition(position, { transaction });
        }

        if (data[7]) {
          const applicationArea = await ctx.model.ApplicationArea.findOne(
            {
              where: {
                name: data[7],
              },
            },
            { transaction }
          );
          await talent.setApplication_area(applicationArea, { transaction });
        }

        if (data[4]) {
          const organizationType = await ctx.model.OrganizationType.findOne(
            {
              where: {
                name: data[4],
              },
            },
            { transaction }
          );
          await talent.setOrganization_type(organizationType, { transaction });
        }

        if (data[8]) {
          const type = await ctx.model.TalentClassfication.findOne(
            {
              where: {
                typeName: data[8],
              },
            },
            { transaction }
          );
          await talent.setTalent_classfication(type, { transaction });
        }

        await transaction.commit();
        num = num + 1;
      } catch (e) {
        console.log(e);
        await transaction.rollback();
        return new Result(null, MsgEnum.SERVER_ERROR);
      }
    }

    return new Result(
      { upload: true },
      `${num}个人才已上传成功，已帮您去除重复人才。`
    );
  }

  async update(data, r) {
    const { ctx } = this;

    let transaction;
    try {
      transaction = await this.ctx.model.transaction();
      const talent = await ctx.model.Talent.findOne(
        { where: { uuid: data.uuid } },
        { transaction }
      );
      // uuid,
      // name: data.name,
      // sex: data.sex,
      // age: data.age,
      // tel: data.tel,
      // email: data.email,
      // role: data.title,
      // education: data.education,
      // fk_applicationArea: data.applicationArea,
      // pk_type: data.talentType,
      // unit: data.unit,
      // filler: data.filler,
      // description: data.description,
      // post: data.position,
      // type: data.type,
      // updateTime: new Date(now),
      const today = new Date();
      const now =
        today.getFullYear() +
        '-' +
        (today.getMonth() + 1) +
        '-' +
        today.getDate();
      console.log('=========================');
      console.log(data);
      await talent.update(
        {
          name: data.name,
          sex: data.sex,
          age: data.age,
          tel: data.tel,
          email: data.email,
          role: data.title,
          education: data.education,
          fk_applicationArea: data.applicationArea,
          pk_type: data.talentType,
          unit: data.unit,
          description: data.description,
          post: data.position,
          type: data.type,
          address: data.address,
          updateTime: new Date(now),
        },
        { transaction }
      );
      const { id } = talent;
      console.log('id:', id);

      await transaction.commit();
      console.log(r.filename);

      if (r.filename !== 'null.pdf') {
        const res = await put(RoleEnum.TALENT, id, r);
        if (res.error) {
          return new Result(null, MsgEnum.SERVER_ERROR);
        }
      }
      return new Result({ upload: true }, MsgEnum.UPLOAD_SUCCESS);
    } catch (e) {
      console.log(e);

      await transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }

  public async getTalentMaps() {
    const mainData = await this.ctx.model.Talent.findAll({
      attributes: ['address'],
    });
    const data: any = {};
    mainData.forEach((v: any) => {
      let add;
      if (v.address?.split(';')[0] === '台湾省') {
        add = '台湾';
      } else {
        add = v.address?.split(';')[1];
      }
      if (!data.hasOwnProperty(add)) {
        data[add] = 1;
      } else {
        data[add]++;
      }
    });
    let dataw = 'lng,lat,name,v\n';
    for (const name in data) {
      if (data.hasOwnProperty(name)) {
        if (areas[name] && name !== undefined && name !== 'undefined') {
          dataw +=
            (areas[name]?.join(',') ?? '0,0') +
            ',' +
            name +
            ',' +
            data[name] +
            '\n';
        } else {
          dataw += '\n';
        }
      }
    }
    return dataw;
  }
}
